function getBollMd(dataList, ma) {
    const dataSize = dataList.length;
    let sum = 0;
    dataList.forEach(data => {
        const closeMa = data.close - ma;
        sum += closeMa * closeMa;
    });
    sum = Math.abs(sum);
    return Math.sqrt(sum / dataSize);
}

const stoch = {
    name: 'BOLLDIV',
    shortName: 'BOLLDIV',
    calcParams: [20, 2],
    figures: [
        // { key: 'divup', title: 'DIVUP: ', type: 'line' },
        { key: 'divupMA5', title: 'DIVUP MA5: ', type: 'line' },  // 添加DIVUP五日均线
        { key: 'divupMA10', title: 'DIVUP MA10: ', type: 'line' }  // 添加DIVUP 10日均线
    ],
    calc: (dataList, indicator) => {
        const params = indicator.calcParams;
        const p = params[0] - 1;
        let closeSum = 0;
        let prevUp = null;
        let divupValues = [];  // 存储最近五个divup值的数组
        let divupValues2 = [];  // 存储最近五个divup值的数组

        return dataList.map((kLineData, i) => {
            const close = kLineData.close;
            const boll = {};
            closeSum += close;
            var ma = 5;
            var ma2 = 1;
            if (i >= p) {
                boll.mid = closeSum / params[0];
                const md = getBollMd(dataList.slice(i - p, i + 1), boll.mid);
                boll.up = boll.mid + params[1] * md;
                boll.dn = boll.mid - params[1] * md;
                if (prevUp != null) {
                    boll.divup = (boll.up + boll.dn) * boll.mid / prevUp;
                }
                prevUp = (boll.up + boll.dn) * boll.mid;  // 更新prevUp为当前的boll.up

                // 更新divupValues数组，添加最新的divup值
                divupValues.push(boll.divup);
                if (divupValues.length > ma) {
                    divupValues.shift();  // 保持数组长度为5
                }

                // 计算五日均线
                if (divupValues.length === ma) {
                    boll.divupMA10 = divupValues.reduce((acc, val) => acc + val, 0) / ma;
                }


                // 更新divupValues数组，添加最新的divup值
                divupValues2.push(boll.divup);
                if (divupValues2.length > ma2) {
                    divupValues2.shift();  // 保持数组长度为5
                }

                // 计算五日均线
                if (divupValues2.length === ma2) {
                    boll.divupMA5 = divupValues2.reduce((acc, val) => acc + val, 0) / ma2;
                }

                closeSum -= dataList[i - p].close;
            }
            return boll;
        });
    }
};

export default stoch;
